package com.bjpowernode.service.impl;

import com.bjpowernode.constant.Constants;
import com.bjpowernode.entity.TTran;
import com.bjpowernode.entity.TUser;
import com.bjpowernode.manager.RedisManager;
import com.bjpowernode.mapper.TTranMapper;
import com.bjpowernode.query.BaseQuery;
import com.bjpowernode.query.TranQuery;
import com.bjpowernode.service.TranService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TranServiceImpl implements TranService {

    @Resource
    private TTranMapper tTranMapper;

    @Resource
    private RedisManager redisManager;

    @Override
    public boolean createTran(TranQuery tranQuery) {
        TTran tTran = new TTran();
        BeanUtils.copyProperties(tranQuery, tTran);

        //设置交易编号（唯一值）
        String onlyNumber = System.currentTimeMillis() + "" + redisManager.generateOnlyNumber(Constants.REDIS_ONLY_NUMBER);
        tTran.setTranNo(onlyNumber);

        //创建时间
        tTran.setCreateTime(new Date());
        //创建人
        TUser authUser = (TUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer currentLoginUserId = authUser.getId();
        tTran.setCreateBy(currentLoginUserId);

        int insert = tTranMapper.insertSelective(tTran);

        return insert >= 1;
    }

    @Override
    public PageInfo<TTran> getTranPage(Integer current) {
        //1.设置PageHelper (第一个参数是查第几页，第二个参数每页查多少条数据)
        PageHelper.startPage(current, Constants.PAGE_SIZE);

        //2.查询数据库表的数据
        List<TTran> list = tTranMapper.selectTranPage(new BaseQuery());

        //3.封装分页数据到PageInfo
        PageInfo<TTran> info = new PageInfo<>(list);

        //4.返回PageInfo对象
        return info;
    }
}
